/**
 * 分页查询方法
 * @param url
 * @param pageNo
 * @param pageSize
 */
function submit(url, pageNo, pageSize) {
    if(pageNo === undefined){
        pageNo = initPageNo;
    }
    if(pageSize === undefined){
        pageSize = initPageSize;
    }

    layui.use(['table', 'laypage','form'], function () {
        let table = layui.table;
        let laypage = layui.laypage;

        let type = $('#dictType').val();
        let code = $('#code').val();
        let name = $('#name').val();
        let dictStatus = $('#dictStatus').val();

        //第一个实例
        table.render({
            elem: '#searchTable'
            ,url: url //数据接口
            ,page: false //开启分页
            ,toolbar: '#tableToolbar'
            ,height: 'full-250'
            , method: 'POST'
            , headers: {"token": getCookie("token")}
            , contentType : "application/json"
            , where: {type:type,code:code,name:name,dictStatus:dictStatus,pageNo:pageNo,pageSize:pageSize}
            ,cols: [[ //表头
                {field: 'dataId',type: 'checkbox'}
                , {field: 'type', title: '字典类型', width: '150', align: 'center'}
                , {field: 'code', title: '字典编码', width: '150',align: 'center'}
                , {field: 'name', title: '字典名称', width: '150',align: 'center'}
                , {field: 'remarks', title: '备注', width: '250', align: 'center'}
                , {field: 'dictStatusName', title: '是否启用', width: '100',align: 'center'}
                , {field: 'right', width: '200', title: '操作', align: 'center', toolbar: '#barSearch'} //添加工具条,
            ]]
            ,parseData: function(res){ //将原始数据解析成 table 组件所规定的数据
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.pageInfo.totalCount, //解析数据长度
                    "pageNo": res.data.pageInfo.pageNo, //解析数据长度
                    "pageSize": res.data.pageInfo.pageSize, //解析数据长度
                    "data": res.data.pageInfo.list //解析数据列表
                };
            }
            ,done:function (res) {
                //校验登陆状态
                checkLogin(res);
                //增加自定义样式
                beautyCell();
                //自定义分页
                laypage.render({
                    elem: 'tablePage'
                    , curr: res.pageNo
                    , count: res.count
                    , limit: res.pageSize
                    ,layout: ['page', 'limit','count', 'skip']
                    ,limits:['20','30','50','100']
                    ,theme: '#1b2b34'
                    ,jump: function(obj,first){
                        if(!first){
                            submit(url, obj.curr, obj.limit);
                        }
                    }
                });
            }
        });

        //工具条
        table.on('tool(searchTable)', function(obj){
            let data = obj.data;
            if(obj.event === 'update'){
                let id = data.id;
                xadmin.open("修改字典","./edit.html?id="+id,500,470);
            }
            if(obj.event === 'delete'){
                let id = data.id;
                let url = serverPre + "/manager/scs/v2/dictionary/remove/"+id;
                confirmMsg(url);
            }
        });

        //头部按钮
        table.on('toolbar(searchTable)', function(obj){
            let checkStatus = table.checkStatus(obj.config.id);
            switch(obj.event){
                case 'create':
                    xadmin.open("新增字典","./add.html",500,470);
                    break;
                case 'export':
                    let data = checkStatus.data;
                    let ids = [];
                    $.each(data, function(i, item){
                        ids.push(item.refId);
                    });
                    exportTemplate(ids);
                    break;
            }
        })

    });
}

/**
 * 新增渠道
 * @param url
 * @param data
 * @returns {boolean}
 */
function saveChannel(url,data) {
    $.ajax({
        url: url,
        data: data,
        type: 'POST',
        contentType: 'application/json',
        headers: {'token': getCookie('token')},
        success: function (res) {
            if (res.code === 0) {
                layui.use('layer',function(){
                    let layer = layui.layer;
                    layer.msg("保存成功!",{
                        icon:1,
                        time:2000,
                        end: function () {
                            var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                            parent.layer.close(index);
                            parent.location.reload();
                        }
                    });
                });
            }
        },
        error: function (err) {
            errorMsg("保存失败")
        }
    });
    return false;
}

/**
 * 删除渠道
 */
function confirmMsg(url) {
    layui.use('layer',function(){
        var layer = layui.layer;
        layer.confirm('确定要删除吗？', {
            btn: ['确定', '取消']
        }, function(index){//按钮一的回调
            $.ajax({
                url: url,
                type: 'GET',
                dataType: 'json',
                async:false,
                headers: {'token': getCookie('token')},
                success: function (res) {
                    if (res.code === 0) {
                        layui.use('layer',function(){
                            let layer = layui.layer;
                            layer.msg("删除成功!",{
                                icon:1,
                                time:2000,
                                end: function () {
                                    layer.close(layer.index);
                                    $('#reloadTemplateData').trigger("click");
                                }
                            });
                        });
                    }else {
                        errorMsg("删除失败")
                    }
                },
                error: function (err) {
                    alert(err);
                }
            });
            return false;
        }, function(index){//按钮二的回调

        });
    })
}

/**
 * 美化按钮样式
 */
function beautyCell() {
    $("[data-field='channelStatusName']").children().each(function (index,item) {
        // debugger
        if(item.textContent === '启用'){
            $(this).css("color","#228b22");
        }
        if(item.textContent === '停用'){
            $(this).css("color","#ff0000");
        }
    })
}

/**
 * 查看窗口
 * @param result
 */
function buildOpenWin(result){
    if(result === undefined || result === null){
        errorMsg("返回数据为空");
    }
    if(result.channelNo !== ""){
        $('#channelNo').val(result.channelNo);
    }
    if(result.channelName !== ""){
        $('#channelName').val(result.channelName);
    }
    if(result.channelAlias !== ""){
        $('#channelAlias').val(result.channelAlias);
    }
    if(result.channelMappingNo !== ""){
        $('#channelMappingNo').val(result.channelMappingNo);
    }
    if(result.createTime !== ""){
        let time = toDateString(result.createTime);
        $('#createTime').val(time);
    }
    if(result.updateTime !== ""){
        let time = toDateString(result.updateTime);
        $('#updateTime').val(time);
    }
    if(result.channelStatusName !== ""){
        $('#channelStatusName').val(result.channelStatusName);
    }
}

/**
 * 编辑窗口
 * @param result
 */
function buildEditWin(form) {
    let id = GetUrlParam("id");
    let url = serverPre + "/manager/scs/v2/dictionary/one/"+id;
    $.ajax({
        type: 'get',
        url: url,
        headers: {"token": getCookie("token")},
        dataType: 'json',
        success: function (result) {
            if (result.code === 0) {
                var data = result.data.vo;
                //封装数据
                $('#id').val(data.id);
                $('#type').val(data.type);
                $('#code').val(data.code);
                $('#name').val(data.name);
                $('#remarks').val(data.remarks);
                if(data.dictStatus === 1){
                    $("[name=dictStatus]:checkbox").prop("checked", true);
                }else {
                    $("[name=dictStatus]:checkbox").prop("checked", false);
                }
                form.render('checkbox');
            }
        }
    });
}

/**
 * 提交表单
 * @param formData
 * @param url
 */
function submitForm(commitData,url) {
    layui.use(['form', 'layedit', 'laydate'], function(){
        var form = layui.form;
        //自定义验证规则
        form.verify({
            channelName: function(value){
            },
            channelAlias: function(value){
            },
            channelStatus: function(value){
            }
        });

        //监听提交
        form.on('submit(submitBtn)', function(data){
            saveChannel(url,commitData);
            return false;
        });
    })
}

function queryDictType(form){
    let url = serverPre + "/manager/scs/v2/dictionary/dictType/list";
    let content = '<option value="">请选择</option>'; //全局变量
    let data = JSON.stringify({'pageNo':'1','pageSize':'999'});
    $.ajax({
        url: url,
        data: data,
        type: 'POST',
        contentType: 'application/json',
        headers: {'token': getCookie('token')},
        success: function (res) {
            if (res.code === 0) {
                let result = res.data.list;
                $.each(result,function (i,item) {
                    let code = item.type;
                    let name = item.type;
                    content += '<option value = "' + code + '">' + name + '</option>'
                });
                $("#dictType").html(content);
                form.render('select');
            }
        },
        error: function (err) {
            errorMsg(err);
        }
    });
}
